/**
 * Created by zyy on 15/9/8.
 * zhangyuyu@superjia.com
 */
(function ($) {
    'use strict';

    var prd = {

        api: function(key){
            var rootPath = '/api/prd';
            return rootPath + {
                list: '',
                create: '/create'
            }[key];
        },

        collection: new (Backbone.Collection.extend({
            model: Backbone.Model,
            parse: function (response, xhr) {
                if (response.code != 200) {
                    return [];
                }
                var items = response.data;
                if (!items) return response;
                return items;
            }
        })),

        init: function (container, options) {
            var self = this;
            self.container = container;
            self.options = options;

            container.html(tpl);

            self.listPanel = container.find('.list');

            self.collection.bind('reset', self.addItems, self);
            self.collection.bind('add', self.addItem, self);

            self.events();

        },

        load: function(projectId, callback) {
            var self = this;
            var container = self.container;
            var options = self.options;

            self.projectId = projectId;

            self.listPanel.empty();

            self.collection.fetch({
                url: self.api('list'),
                data: {
                    projectId: projectId
                },
                method: 'get',
                success: function (collection, response, opt) {
                    if(options.prdId) {
                        self.selectItem(options.prdId);
                    }
                },
                error: function () {
                    callback && callback(null)
                }
            })
        },

        setOptions: function(options) {
            this.options = $.extend({}, this.options, options);
        },

        getPrd: function(prdId, callback) {
            var self = this;
            $.ajax({
                url: self.api('list'),
                data: {
                    _id: prdId
                },
                success: function(res){
                    if(res.code == 200) {
                        callback && callback(res.data);
                    }
                }
            })
        },

        events: function() {
            var self = this;
            var container = self.container;

            container.on('click', '.create-btn', function() {
                var dialog = self.createdialog = new App.common.Dialog({
                    title: '创建prd',
                    isConfirm: true,
                    message: createTpl,
                    okCallback: function() {
                        var nameInput = dialog.find('input[name="name"]');
                        var name = $.trim(nameInput.val());
                        if (name) {
                            self.createPrd(name);
                        }
                    }
                });
            });
        },

        selectItem: function(prdId) {
            var self = this;
            var collection = self.collection;
            if(!prdId) return false;
            collection.where({_id: prdId})[0].trigger('selected');
        },

        createPrd: function(name) {
            var self = this;

            $.ajax({
                url: self.api('create'),
                type: 'post',
                data: {
                    projectId: self.projectId,
                    name: name
                },
                success: function(res) {
                    if (res.code == 200) {
                        self.collection.add([res.data]);
                    }
                }
            });
        },

        addItems: function(collection, options) {
            var self = this
            collection.each(function(model) {
                self.addItem(model, collection)
            });
        },

        addItem: function(model, collection, options) {
            var self = this
            var view = new prdView({
                model: model
            })
            self.listPanel.append(view.render().$el);
        }
    };

    var prdView = Backbone.View.extend({
        className: 'prd-item stateful',
        events: {
            'click': 'itemClickHandler'
        },
        initialize: function() {
            var self = this
            self.listenTo(self.model, 'change', self.render);
            self.listenTo(self.model, 'selected', self.selected);
        },
        render: function() {
            var self = this
            var data = self.model.toJSON();


            self.$el.html(template.draw(itemTpl, data)).attr('href', '/prd/' + data._id);

            return self
        },
        itemClickHandler: function() {
            var self = this
            var data = null
            var item = data = self.model.toJSON();

            self.selected();
        },

        selected: function() {
            this.$el.siblings().removeClass('active').end().addClass('active');
        }
    });

    var tpl = '' +
        '<div class="mod-prd">' +
        '   <div class="create-btn btn btn-primary">创建prd</div>' +
        '   <div class="list"></div>' +
        '</div>';

    var createTpl = '' +
        '<div class="prd-create">' +
        '   <input name="name" autofocus class="form-control" placeholder="prd名称"/>' +
        '</div>';

    var itemTpl = '' +
        '<span>{{name}}</span>'

    App.modules.prd = prd;
})(jQuery);